from apps.system.user.baseViews import *
from apps.system.user.service import replaceToken, findParentIsExist
from apps.pay.recordIncomes.dao import RecordIncomesDao

# 管理员账号
class AdminViewSet(BaseUserViewSet):
    serializer_class = AdminModelSerializer

    def get_queryset(self):
        params = getRequestParams(self.request)
        _users = UserDao().findAllAdmin()
        return _users

    '''创建管理员'''
    @action(methods=['post'], detail=False)
    def createAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('role'):
            return Response(response_message('role参数必填'))
        if not params.get('username'):
            return Response(response_message('username参数必填'))
        data = {}
        data['lessee'] = params.get('lessee')
        data['role'] = params.get('role')
        data['username'] = params.get('username')
        data['password'] = params.get('password')
        data['phone'] = params.get('phone')
        data['nickname'] = params.get('nickname')
        data['realname'] = params.get('realname')
        data['status'] = params.get('status')
        data['checkStatus'] = params.get('checkStatus') or 'PASS'
        if isEmptyStr(params.get('password')):
            data['password'] = random_uuid()
        UserDao().create(data)

        return Response(response_success('创建成功'))

# tree
class UserTreeViewSet(BaseUserViewSet):
    serializer_class = UserTreeModelSerializer

    def get_queryset(self):
        params = getRequestParams(self.request)
        _lists = UserDao().findAllUserByLessee(params.get('lessee'))
        parentId = params.get('parentId')
        parentCode = params.get('parentCode')
        if parentId:
            _lists = _lists.filter(parent = parentId)
        elif parentCode:
            _lists = _lists.filter(code=parentCode)
        else:
            _lists = _lists.filter(parent__isnull=True)
        return _lists.order_by('id')

class UserViewSet(BaseUserViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = UserDao().findAllUserByLessee(params.get('lessee'))
        return _list

    '''账号密码登录'''
    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def login(self, request):
        params = getRequestParams(self.request)
        captcha_text = request.session.get('captcha_text')
        _users = UserDao().findAllAdmin().filter(username=params.get('username'), password=params.get('password'))
        # 更新token
        if not _users.exists():
            return Response(response_message('账号或密码错误！'))
        if _users.first().status == 0:
            return Response(response_message('该账号已被禁用，等联系管理员！'))
        _shops = _users.first().admin_shop.all()
        if _shops.count()>0 and _shops.filter(checkStatus="PASS").count()<=0:
            return Response(response_message('该账号该账号关联的商户暂未通过审核，请稍后重试！'))
        if captcha_text.lower() != params.get('code').lower():
            return Response(response_message('验证码错误！'))
        _userId = _users.first().id
        token = replaceToken(_userId)
        return Response(response_success({'token': token.key}))

    '''获取用户信息'''

    @action(methods=['post'], detail=False)
    def getUserInfo(self, request):
        params = getRequestParams(self.request)
        obj = UserDao().findOneByObjId(self.request.user.id)
        model = UserModelDetailSerializer(obj).data
        return Response(response_success(model))
    
    @action(methods=['post'], detail=False)
    def getAdminInfo(self, request):
        params = getRequestParams(self.request)
        obj = UserDao().findOneByObjId(self.request.user.id)
        model = AdminModelSerializer(obj).data
        return Response(response_success(model))

    @action(methods=['post'], detail=False)
    def getUserInfoById(self, request):
        params = getRequestParams(self.request)
        if not params.get('obj_id'):
            return Response(response_message(('obj_id参数必填')))
        obj = UserDao().findOneByObjId(params.get('obj_id'))
        model = UserModelDetailSerializer(obj).data
        return Response(response_success(model))

    '''更新用户信息'''

    @action(methods=['post'], detail=False)
    def updateUser(self, request):
        params = getRequestParams(self.request)
        UserDao().update(request.user.id, params)
        return Response(response_success('修改成功'))

    '''退出登录'''

    @action(methods=['post'], detail=False, authentication_classes=[], permission_classes=[])
    def logout(self, request):
        params = getRequestParams(request)
        _tokens = Token.objects.filter(key=params.get("token"))
        if _tokens.count() > 0 and _tokens.first().user.username != 'openshop':
            _tokens.delete()
        return Response(response_success("操作成功"))

    '''管理员修改密码'''

    @action(methods=['post'], detail=False)
    def updatePwdForAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('oldPassword'):
            return Response(response_message("旧密码不能为空"))
        if not params.get('password'):
            return Response(response_message("新密码不能为空"))
        _user = UserModel.objects.get(id=params.get('userId'))
        if _user.password != params.get('oldPassword'):
            return Response(response_message("旧密码验证失败！"))
        _user.password = params.get('password')
        _user.save()
        return Response(response_success('密码修改成功'))

    '''管理员重置密码'''

    @action(methods=['post'], detail=False)
    def resetPwdForAdmin(self, request):
        params = getRequestParams(request)
        if not params.get('password'):
            return Response(response_message("新密码不能为空"))
        _user = UserModel.objects.get(id=params.get('userId'))
        _user.password = params.get('password')
        _user.save()
        # 密码重置之后，删除token
        old_token = Token.objects.filter(user_id=_user.id)
        old_token.delete()
        return Response(response_success('密码修改成功'))

    '''获取用户信息通过用户code或者手机号'''
    @action(methods=['post'], detail=False)
    def getUserInfoByCode(self, request):
        params = getRequestParams(request)
        if not params.get('memberCode'):
            return Response(response_message('会员ID或者手机号不能为空'))
        new_users = UserDao().findAll().filter(Q(code=params.get('memberCode')) | Q(phone=params.get('memberCode')), role='custom')
        if new_users.count() <= 0:
            return Response(response_message('会员ID或者手机号不存在'))
        userInfo = UserModelSerializer(new_users.first()).data
        return Response(response_success(userInfo))
    
    '''修改用户推荐人'''
    @action(methods=['post'], detail=False)
    def updateUserForParent(self, request):
        params = getRequestParams(request)
        if not params.get('userId'):
            return Response(response_message('userId必填'))
        if not params.get('parentId'):
            return Response(response_message('parentId必填'))
        if params.get('userId') == params.get('parentId'):
            return Response(response_message('不能把自己设为推荐人'))
        _parents = UserDao().findAllUser().filter(id=params.get('parentId'))
        if _parents.count()<1:
            return Response(response_message('推荐人不存在'))
        _user = UserModel.objects.get(id=params.get('userId'))
        _parent = UserModel.objects.get(id=params.get('parentId'))
        if _user.parent == _parent:
            return Response(response_message('推荐关系已存在，无需需改'))
        # 检查推荐人的上级是否有该用户
        isExist = findParentIsExist(_parent, _user)
        if isExist:
            return Response(response_message('不能设置自己的团队成员为推荐人'))
        # 修改推荐人
        UserDao().update(_user.id, {'parent': _parent.id})
        return Response(response_success('修改成功'))
    
    '''充值积分'''
    @action(methods=['post'], detail=False)
    def updateUserForAddIncome(self, request):
        params = getRequestParams(request)
        if not params.get('payway'):
            return Response(response_message('payway参数必填'))
        if not params.get('money'):
            return Response(response_message('请填写金额'))
        if not params.get('userId'):
            return Response(response_message('userId参数必填'))
        _payway = params.get('payway')

        _user = UserDao().findOneByObjId(params.get('userId'))
        UserDao().addWallet(_payway, _user, params.get('money'))
        data = {}
        data['scene'] = 'addIncomeFromAdmin'
        data['user'] = _user.id
        data['fromUser'] = self.request.user.id
        data['orderId'] = ''
        data['money'] = params.get('money')
        data['payway'] = _payway
        data['changeWay'] = 'add'
        data['orderStatus'] = 'FINISH'
        data['remark'] = params.get('remark')
        RecordIncomesDao().create(data)
        return Response(response_success('充值成功'))

    '''扣除积分'''
    @action(methods=['post'], detail=False)
    def updateUserForSubIncome(self, request):
        params = getRequestParams(request)
        if not params.get('payway'):
            return Response(response_message('payway参数必填'))
        if not params.get('money'):
            return Response(response_message('请填写金额'))
        if not params.get('userId'):
            return Response(response_message('userId参数必填'))
        _payway = params.get('payway')

        _user = UserDao().findOneByObjId(params.get('userId'))
        UserDao().subWallet(_payway, _user, params.get('money'))
        data = {}
        data['scene'] = 'subIncomeFromAdmin'
        data['user'] = _user.id
        data['fromUser'] = self.request.user.id
        data['orderId'] = ''
        data['money'] = params.get('money')
        data['payway'] = _payway
        data['changeWay'] = 'sub'
        data['orderStatus'] = 'FINISH'
        data['remark'] = params.get('remark')
        RecordIncomesDao().create(data)
        return Response(response_success('扣除成功'))
